package com.zzyl.nursing.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 * 
 * @author xiexiaoyu
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

   @Autowired
   private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AIModelInvoker aiModelInvoker;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment)
    {
        //1 组装prompt，将体检报告和模板拼接
        String prompt=getPrompt(healthAssessment.getIdCard());
        //2调用千帆大模型分析体检报告
        String result = aiModelInvoker.qianfanInvoker(prompt);
        if(StringUtils.isEmpty(result)){
            throw new BaseException("千帆大模型分析体检报告失败！");
        }
        HealthReportVo healthReportVo = JSONUtil.toBean(result, HealthReportVo.class);
        //3将评估结果保存到数据库中
       Long id= insertHealthReport(healthAssessment,healthReportVo);
        //4返回id
        return id;
    }
    /**
     * 保存体检报告
     * */
    private Long insertHealthReport(HealthAssessment healthAssessment, HealthReportVo healthReportVo) {
        //生日,年龄，性别
        String idCard = healthAssessment.getIdCard();
        healthAssessment.setBirthDate(IDCardUtils.getBirthDateByIdCard(idCard));
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(idCard));
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(idCard));
        //健康评分
        double healthScore = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthScore));
        //危险等级
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        //建议入住
        healthAssessment.setSuggestionForAdmission(healthScore >= 60 ? 0:1);
        //推荐护理等级
        String nursingLevelName =getNarsLevel(healthScore);
        healthAssessment.setNursingLevelName(nursingLevelName);
        //入住情况
        healthAssessment.setAdmissionStatus(1);
        //总检日期
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        //评估时间
        healthAssessment.setAssessmentTime(LocalDateTime.now());
        //报告总结
        healthAssessment.setReportSummary(healthReportVo.getSummarize());
        //疾病风险
        healthAssessment.setDiseaseRisk(JSONUtil.toJsonStr(healthReportVo.getRiskDistribution()));
        //异常分析
        healthAssessment.setAbnormalAnalysis(JSONUtil.toJsonStr(healthReportVo.getAbnormalData()));
        //健康系统分值
        healthAssessment.setSystemScore(JSONUtil.toJsonStr(healthReportVo.getSystemScore()));

        healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();
    }

    private String getNarsLevel(double healthScore) {
        if(healthScore>100||healthScore<0){
            throw new BaseException("健康评分异常！");
        }
        if(healthScore>=90){
            return "四级护理等级";
        }else if(healthScore>=80){
            return "三级护理等级";
        }else if(healthScore>=70){
            return "二级护理等级";
        }else{
            return "一级护理等级";
        }

    }

    /**
     * 获取prompt
     * */
    private String getPrompt(String idCard) {
        try {
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("prompts\\HealthReport.txt");
            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(isr);
            String content = (String)redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, idCard);

            //优化：取出体检报告内容后，删除redis缓存中的数据
            redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT, idCard);

            StringBuilder sb=new StringBuilder();
            String line;
            while ((line = br.readLine()) != null){
                sb.append(line);
                if(line.contains("体检内容如下：")){
                    sb.append(content);
                }
            }
            String prompt = sb.toString();

            return prompt;
        } catch (IOException e) {
            throw new BaseException("获取prompt失败！");
        }
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.deleteById(id);
    }
}
